package com.lg.distributed.transaction.service.impl;

import com.lg.distributed.transaction.config.MyMQConfig;
import com.lg.distributed.transaction.domain.MqMessage;
import com.lg.distributed.transaction.domain.SendMessage;
import com.lg.distributed.transaction.dao.MqMessageDao;
import com.lg.distributed.transaction.service.MqMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author by Mr. Li 2020/12/11 10:27
 */
@Service
@Slf4j
public class MqMessageServiceImpl implements MqMessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageDao mqMessageDao;

    @Override
    public void save(MqMessage mqMessage) {
        mqMessageDao.insert(mqMessage);
    }

    @Override
    public void saveOrUpdate(MqMessage mqMessage) {
        mqMessageDao.updateByPrimaryKey(mqMessage);
    }

    @Override
    public void send() {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setContent("你好啊，rabbitmq的最终一致性");
        sendMessage.setId(UUID.randomUUID().toString());

        rabbitTemplate.convertAndSend(MyMQConfig.DISTRIBUTED_TRANSACTION_EVENT_EXCHANGE,
                MyMQConfig.DISTRIBUTED_TRANSACTION_KEY,
                sendMessage);
    }

    @Override
    public List<MqMessage> selectByMessageStatusNo1() {
        return mqMessageDao.selectByMessageStatusNo1();
    }

    @Override
    public void sendMq() {
        MqMessage sendMessage = new MqMessage();
        sendMessage.setContent("rabbitMq 的 分布式事务最终一致性解决方案");
        sendMessage.setCreateTime(new Date());
        sendMessage.setMessageId(UUID.randomUUID().toString());
        sendMessage.setRoutingKey( MyMQConfig.DISTRIBUTED_TRANSACTION_KEY);
        sendMessage.setToExchane(MyMQConfig.DISTRIBUTED_TRANSACTION_EVENT_EXCHANGE);
        rabbitTemplate.convertAndSend(MyMQConfig.DISTRIBUTED_TRANSACTION_EVENT_EXCHANGE,
                MyMQConfig.DISTRIBUTED_TRANSACTION_KEY,
                sendMessage);
    }
}
